// import Taro from '@tarojs/taro';
import { goodsDetail, cart } from '../../../utils/api';

export default {
  namespace: 'detail',
  state: {
    data: [],
    key: '72eed010c976e448971655b56fc2324e',
    v: '1.0'
  },

  effects: {
    * getDetail({ payload }, { select, call, put }) {
      const { key, v } = yield select(state => state.index)
      const result = yield call(goodsDetail, {
        key,
        v,
        ...payload
      })
      yield put({
        type: 'updateState',
        payload: {
          data: result
        }
      })
    },

    * selectSku({ payload }, { __, put }) {
      yield put({
        type: 'updateSelectSku',
        payload
      })
    },

    * addCart({ payload }, { call, put }) {
      yield call(cart, {
        ...payload
      })
      yield put({
        type: 'cart',
        payload
      })
    },
  },

  reducers: {
    updateState(state, { payload: data }) {
      return { ...state, ...data }
    },
    updateSelectSku(state, { payload }) {
      let data = state.data;
      for (let i = 0; i < data.sku.length; i++) {
        if (payload.name_id === data.sku[i].id) {
          for (let j = 0; j < data.sku[i].skuValue.length; j++) {
            if (payload.value_id === data.sku[i].skuValue[j].id && data.sku[i].skuValue[j].selected == 0) {
              data.sku[i].skuValue[j].selected = 1;
            }else{
              data.sku[i].skuValue[j].selected = 0;
            }
          }
        }
      }
      return { ...state, ...JSON.parse(JSON.stringify(data)) }
    },
    cart(state, { payload }){
      console.log(payload);
    }
  }

}
